package com.itheima.task;

import com.itheima.common.utils.AliOssUtil;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Slf4j
public class OSSImageCleanupTask {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 每隔10秒检查一次数据库和OSS中的图片，如果数据库中没有图片，则从OSS中删除图片
     * 注意删除的名字不需要带全路径，之间是UUID生成的文件名.后缀即可
     */
    @Scheduled(cron = "0 0 0 * * *") // 每天零点
//    @Scheduled(cron = "0/1 * * * * *") // 每测试使用
    @Transactional(rollbackFor = Exception.class)
    public void cleanup() {
        log.info("开始检查并清理OSS图片");
        // aliOssUtil.delete("5672d956-63b6-49a8-a88e-4ce632bfa9b5.jpg");

        // 获取数据库所有数据项的图片url存储到redis的集合中
        SetOperations<String, String> setOperations = redisTemplate.opsForSet();

        // 获取两个集合的差集
        Set<String> difference = setOperations.difference("imgFromOSS", "imgFromDB");
        log.info("差集为{}", difference);

        // 从阿里oss中删除图片url
        Objects.requireNonNull(difference).forEach(url -> {
            try {
                aliOssUtil.delete(url.substring(url.lastIndexOf("/") + 1));
                log.info("从阿里云OSS中删除图片成功，路径为{}", url);
                setOperations.remove("imgFromOSS", url);
                log.info("从redis中删除图片成功，路径为{}", url);
            } catch (Exception e) {
                log.error("删除图片失败，路径为{}", url);
            }
        });

    }
}
